package com.android.support.lib.universal.die;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import android.app.Activity;

/**
 * 静止一段时间后自动关闭此activity 
 * 调用案例： 参数一：当前要销毁的Activity 参数二：自动销毁的时间,单位 秒
 * InactivityTimer inactivityTimer=new InactivityTimer(this, 3);
 * 
 */
public final class InactivityTimer {

	private static int INACTIVITY_DELAY_SECONDS = 1 * 60;// 指定activity消失的时间，以秒为单位！

	private final ScheduledExecutorService inactivityTimer = Executors
			.newSingleThreadScheduledExecutor(new DaemonThreadFactory());
	private final Activity activity;
	private ScheduledFuture<?> inactivityFuture = null;

	/**
	 * 
	 * @param activity
	 *            当前的Activity
	 * @param INACTIVITY_DELAY_SECONDS
	 *            自动销毁 时间,单位 秒
	 */
	public InactivityTimer(Activity activity, int INACTIVITY_DELAY_SECONDS) {
		this.activity = activity;
		this.INACTIVITY_DELAY_SECONDS = INACTIVITY_DELAY_SECONDS;
		onActivity();
	}

	public void onActivity() {
		cancel();
		inactivityFuture = inactivityTimer.schedule(
				new FinishListener(activity), INACTIVITY_DELAY_SECONDS,
				TimeUnit.SECONDS);
	}

	private void cancel() {
		if (inactivityFuture != null) {
			inactivityFuture.cancel(true);
			inactivityFuture = null;
		}
	}

	public void shutdown() {
		cancel();
		inactivityTimer.shutdown();
	}

	private static final class DaemonThreadFactory implements ThreadFactory {
		public Thread newThread(Runnable runnable) {
			Thread thread = new Thread(runnable);
			thread.setDaemon(true);
			return thread;
		}
	}

}
